package com.will.yuaiagent.tools;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author will
 * @since 2025/7/13 17:20
 * 网页搜索工具
 */
@Component
public class WebSearchTool {

    //searchAPI 的搜索接口地址
    private static final String SEARCH_API_URL = "https://www.searchapi.io/api/v1/search";

    @Value("${search.api}")
    private String apiKey;


    @Tool(description = "Search for information from Baidu search Engine ")
    public String searchWeb(@ToolParam(description = "Search query keyword" ) String query) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("q", query);
        paramMap.put("api_key", apiKey);
        paramMap.put("engine","baidu");
        try {
            String response = HttpUtil.get(SEARCH_API_URL, paramMap);
            //取出返回结果的前五条
            JSONObject jsonObject = JSONUtil.parseObj(response);
            //提取organic_results字段
            JSONArray organicResults = jsonObject.getJSONArray("organic_results");
            List<Object> objects = organicResults.subList(0, 2);
            //拼接搜索结果为字符串
            return objects.stream().map(o -> {
                JSONObject tmpJSONObject = (JSONObject) o;
                return tmpJSONObject.toString();
            }).collect(Collectors.joining(","));
        }catch (Exception e){
            return "Error searching Baidu: "+ e.getMessage();
        }
    }
}
